<template>
  <div id="menuConfiguration">
    <el-card class="box-card">
      <!-- 头部 -->
      <template #header>
        <div class="card-header">
          <div class="card-header-left">
            <el-icon @click="$router.back()">
              <ArrowLeftBold />
            </el-icon>
            <span>{{ pageTitle }}</span>
          </div>
          <el-button
            type="primary"
            class="height40"
            v-if="!historymode"
            @click="headClickAddVersion"
            >发布版本</el-button
          >
        </div>
      </template>
      <!-- 信息展示 -->
      <div class="info">
        <span>正式服：</span>
        <span>{{ prod_deployment.taskid }}</span>
        <span> {{ prod_deployment.online_time }} </span>
        <span>
          <el-tooltip
            class="box-item"
            effect="light"
            :raw-content="true"
            :content="formatArrayForTooltip(prod_deployment?.oks) || '空'"
            placement="top"
          >
            <span> {{ prod_deployment?.oks?.length }} </span>
          </el-tooltip>
          |
          <el-tooltip
            class="box-item"
            effect="light"
            :raw-content="true"
            :content="formatArrayForTooltip(prod_deployment?.errors) || '空'"
            placement="top"
          >
            <span style="color: red">
              {{ prod_deployment?.errors?.length }}
            </span>
          </el-tooltip>

          |
          <el-tooltip
            class="box-item"
            effect="light"
            :raw-content="true"
            :content="formatArrayForTooltip(prod_deployment?.offines) || '空'"
            placement="top"
          >
            <span style="color: red">
              {{ prod_deployment?.offines?.length }}
            </span>
          </el-tooltip>
        </span>
        <span>{{ prod_deployment.online_crc }}</span>
      </div>
      <div class="info">
        <span>测试服：</span>
        <span>{{ test_deployment.taskid }}</span>
        <span> {{ test_deployment.online_time }} </span>
        <span>
          <el-tooltip
            class="box-item"
            effect="light"
            :raw-content="true"
            :content="formatArrayForTooltip(test_deployment?.oks) || '空'"
            placement="top"
          >
            <span> {{ test_deployment?.oks?.length }} </span>
          </el-tooltip>
          |
          <el-tooltip
            class="box-item"
            effect="light"
            :raw-content="true"
            :content="formatArrayForTooltip(test_deployment?.errors) || '空'"
            placement="top"
          >
            <span style="color: red">
              {{ test_deployment?.errors?.length }}
            </span>
          </el-tooltip>

          |
          <el-tooltip
            class="box-item"
            effect="light"
            :raw-content="true"
            :content="formatArrayForTooltip(test_deployment?.offines) || '空'"
            placement="top"
          >
            <span style="color: red">
              {{ test_deployment?.offines?.length }}
            </span>
          </el-tooltip>
        </span>
        <span>{{ test_deployment.online_crc }}</span>
      </div>
      <div class="info">
        <span>自动开关：</span>
        <span>{{ isauto ? '自动' : '手动' }}</span>
      </div>
      <!-- 表格 -->
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
      >
        <el-table-column prop="id" label="标识" align="center" width="60" />
        <el-table-column
          prop="name"
          label="项目名称"
          align="center"
          width="120px"
        >
          <template #default="scope">
            <p>{{ scope.row.username }}</p>
            <p>{{ scope.row.pjname }}</p>
            <p>{{ scope.row.pjnumber }}</p>
            <p>{{ scope.row.remark }}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="branch"
          label="版本/分支"
          align="center"
          width="100px"
        >
          <template #default="scoped">
            <p>{{ scoped.row.branch }}</p>
            <p style="color: red; font-size: 12px">
              {{ scoped.row.isreleaseversion ? '已发布正式服' : '' }}
            </p>
            <p style="color: red; font-size: 12px">
              {{ scoped.row.istestversion ? '已发布测试服' : '' }}
            </p>
            <p style="color: red; font-size: 12px">
              {{ scoped.row.tag ? scoped.row.tag.substring(0, 8) : '' }}
            </p>
          </template>
        </el-table-column>
        <el-table-column label="时间" align="center" width="240px">
          <template #default="scope">
            <p>添加时间：{{ scope.row.addTime }}</p>
            <p>打包时间：{{ scope.row.packTime }}</p>
            <p>测试完成：{{ scope.row.testTime }}</p>
            <p>发布时间：{{ scope.row.publishTime }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="" label="运行状态" align="center">
          <template #default="scope">
            <div
              class=""
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <p style="text-align: left; padding-right: 10px">
                {{ scope.row.runlog[0].substring(0, 50) }}
              </p>
              <p
                @click="cope(scope.row.runlog[0])"
                style="color: blue; width: 100px; cursor: pointer"
              >
                复制
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="" label="状态" align="center" width="120px">
          <template #default="scope">
            {{ mapStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="date" label="操作" width="500" align="center">
          <template #header>
            <span>
              操作
              <el-tooltip
                class="item"
                effect="light"
                content="0:发布失败;1:打包生成中;2:待部署;3:测试中（程序自动部署到测试服务器）;4:测试未通过;5::测试通过可发布，6，布署到正式服务器"
                placement="top"
              >
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <template #default="scope">
            <div class="alitem">
              <div
                class="icon-button"
                v-if="![1, 2, 6].includes(scope.row.status) && scope.row.id > 0"
                @click="headClick(scope.row, '1')"
              >
                <i class="iconfont icon-wuliaoxiadan" />
                <span>重新打包</span>
              </div>

              <div
                class="icon-button"
                v-if="[3].includes(scope.row.status) && scope.row.id > 0"
                @click="headClick(scope.row, '5')"
              >
                <i class="iconfont icon-ceshitongguo" />
                <span>测试通过</span>
              </div>

              <div
                class="icon-button"
                v-if="[3].includes(scope.row.status) && scope.row.id > 0"
                @click="headClick(scope.row, '4')"
              >
                <i class="iconfont icon-ceshiweitongguo" />
                <span>测试未通过</span>
              </div>

              <div
                class="icon-button"
                v-if="[5, 6].includes(scope.row.status) && scope.row.id > 0"
                @click="headClick(scope.row, '8')"
              >
                <i class="iconfont icon-juduan" />
                <span>部署到测试</span>
              </div>

              <div
                class="icon-button"
                v-if="
                  [5, 6].includes(scope.row.status) &&
                  scope.row.branch == 'release' &&
                  scope.row.id > 0
                "
                @click="headClick(scope.row, '6')"
              >
                <i class="iconfont icon-juduan" />
                <span>部署到正式</span>
              </div>
              <div
                class="icon-button"
                v-if="![1, 2, 6].includes(scope.row.status) && scope.row.id > 0"
                @click="headClick(scope.row, '-1')"
              >
                <i class="iconfont icon-shanchu" />
                <span>删除</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="right" style="margin-top: 20px" v-if="searchData.total">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="searchData.page"
            v-model:page-size="searchData.pageSize"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="searchData.total"
            @size-change="getList"
            @current-change="getList"
          />
        </el-config-provider>
      </div>
    </el-card>
  </div>

  <!-- 新增 -->
  <el-dialog
    v-model="dialogFormVisible"
    title="新增发布"
    width="500"
    @close="closeDialog"
  >
    <el-form :model="form">
      <el-form-item label="项目标号: " :label-width="formLabelWidth">
        <p>{{ form.pjnumber }}</p>
      </el-form-item>
      <el-form-item label="分支: " :label-width="formLabelWidth">
        <el-input
          v-model="form.branch"
          autocomplete="off"
          maxlength="30"
          placeholder="请输入'release/dev'或者其他分支"
        />
      </el-form-item>
      <el-form-item label="备注: " :label-width="formLabelWidth">
        <el-input v-model="form.remark" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import {
  projectsInfoList,
  updateversionstatus,
  delversion,
  addversion,
} from '@/api/system/versionManage';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref } from 'vue';

const route = useRoute();
const queryInfo = ref(JSON.parse(route.query.val));
console.log('queryInfoqueryInfoqueryInfo', queryInfo);
const prod_deployment = ref('');
const test_deployment = ref('');
const historymode = queryInfo.value.historymode;
const pageTitle = historymode ? '版本发布历史' : '版本详情列表';
const searchData = ref({
  page: 1,
  pageSize: 10,
  total: '',
});

const tableData = ref([]);
const isauto = ref(false);

const dialogFormVisible = ref(false);
const formLabelWidth = '80px';
const branchError = ref(false);
const form = ref({
  pjnumber: '',
  branch: '',
  remark: '',
});

// countent 内容转换
const formatArrayForTooltip = (array) => {
  if (!Array.isArray(array)) {
    return ''; // 如果传入的不是数组，返回空字符串
  }
  return array.join('<br/>'); // 使用 <br/> 换行符连接数组元素
};

// 获取列表
const getList = () => {
  const data = {
    pjnumber: queryInfo.value.pjnumber,
    history: historymode ? 1 : 0,
  };
  projectsInfoList({ ...data, ...searchData.value }).then((res) => {
    isauto.value = res.data.isauto;
    tableData.value = res.data.data;
    searchData.value.total = res.data.total;
    prod_deployment.value = res.data.prod_deployment;
    test_deployment.value = res.data.test_deployment;
  });
};
getList();

// 匹配状态
const mapStatus = (status) => {
  const statusMap = {
    0: '发布失败',
    1: '待打包',
    2: '待部署到测试',
    3: '测试中',
    4: '测试未通过',
    5: '测试通过',
    6: '已发布',
  };

  return statusMap[status] || status;
};

// 操作按钮
const headClick = (val, status) => {
  const data = {
    id: val.id,
    status: status,
  };
  if (status == '6') {
    ElMessageBox.prompt('请输入发布指令', '发布正式版', {
      confirmButtonText: '发布',
      cancelButtonText: '取消',
      inputPattern: /^[^\s]{1,10}$/, // 输入正则，去掉空格，限制1到10个字符
      inputErrorMessage: '请输入正确的指令',
    })
      .then(({ value }) => {
        data.operpwd = value;
        // 调用接口并处理返回结果
        updateversionstatus(data).then((res) => {
          if (res.code === 20000) {
            ElMessageBox.alert('已发布成功', '发布通知', {
              confirmButtonText: '确定',
            });
            getList();
          } else {
            ElMessageBox.alert('发布失败 ' + res.msg, '发布通知', {
              confirmButtonText: '确定',
            });
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消操作',
        });
      });
  } else {
    ElMessageBox.confirm('你确定要继续吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        if (status == '-1') {
          delversion({ id: val.id }).then((res) => {
            if (res.code === 20000) {
              ElMessage.success('删除成功');
              getList();
            }
          });
        } else {
          updateversionstatus(data).then((res) => {
            if (res.code === 20000) {
              ElMessage.success('操作成功');
              getList();
            }
          });
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消操作',
        });
      });
  }
};
const cope = (text) => {
  navigator.clipboard
    .writeText(text)
    .then(() => {
      ElMessage.success('复制成功');
    })
    .catch(() => {
      ElMessage.error('复制失败');
    });
};
// 新增版本-打开弹窗
const headClickAddVersion = () => {
  dialogFormVisible.value = true;
  form.value.pjnumber = queryInfo.value.pjnumber;
};

// 提交-新增版本
const submitForm = () => {
  if (!form.value.branch) {
    branchError.value = true;
  } else {
    addversion(form.value).then((res) => {
      if (res.code === 20000) {
        ElMessage.success('添加成功');
        dialogFormVisible.value = false;
        form.value = {};
        getList();
      }
    });
  }
};

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false;
  form.value = {};
};
</script>

<style lang="scss" scoped>
.box-card {
  margin: 20px;

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .card-header-left {
      display: flex;
      flex-direction: row;
      align-items: center;
      gap: 20px;
    }
  }
}
.alitem {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 20px;
  .icon-button {
    display: flex;
    flex-direction: row;
    align-items: center;
    cursor: pointer;
  }
}
.info {
  margin-bottom: 30px;
  gap: 20px;
  span {
    display: inline-block;
    margin: 0 20px;
  }
  & > span:first-child {
    width: 80px;
    text-align: right;
  }
}
</style>
